﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Sustainalytics.Caching;
using Sustainalytics.ScreeningTool.BL;

namespace Sustainalytics.PregenerateScreeningReports.Service
{
    public class ClaimsReaderForISINCUSIPClaims
    {
        private static IAppRedisCache _redisCache;        
        public ClaimsReaderForISINCUSIPClaims(string redisAddress, int databaseId)
        {          
            if (_redisCache == null)
                _redisCache = new AppRedisCache(redisAddress, databaseId);

        }
        public ClaimsPrincipal CollectAccountClaimsForISINAndCUSIP(string accountName)
        {
            string ISINClaim = CUSIPISINClaimsCheckerBL.CLAIMTYPE_ISIN;
            string CUSIPClaim = CUSIPISINClaimsCheckerBL.CLAIMTYPE_CUSIP;
            string expected = CUSIPISINClaimsCheckerBL.CLAIMVALUE;


            var claimsForAccount = _redisCache.GetSet(accountName);
            if (claimsForAccount == null)
                throw new ApplicationException("claimsForAccount id null for account" + accountName);
            
            var claims = new List<Claim>();
            if (claimsForAccount.ToList().Exists(x => x.Contains(ISINClaim) && x.Contains(expected)))
                claims.Add(new Claim(ISINClaim, expected));
            if (claimsForAccount.ToList().Exists(x => x.Contains(CUSIPClaim) && x.Contains(expected)))
                claims.Add(new Claim(CUSIPClaim, expected));

            var ci      = new ClaimsIdentity(claims, "claims");
            var result  = new ClaimsPrincipal(ci);
            return result;
        }
        
    }
}
